<?php
require_once(dirname(__FILE__).'/../config/db_connect.php');

class Departement {

    private $error = array();
    private $name;
    private $abreviation;
    private $id;

    public function setValues($data) {
       $this->id =  empty($data['id']) ? '' : strip_tags(trim($data['id']));
       $this->name = empty($data['name']) ? '' : strip_tags(trim($data['name']));
       $this->abreviation =  empty($data['abreviation']) ? '' : strip_tags(trim($data['abreviation']));
    }
    public function reset() {
       $this->id = '' ;
       $this->name = '';
       $this->abreviation = '';
    }

    public function save($data) {
        
        $this->setValues($data);
        if($this->getId()){
        		if($this->validate()){
        			 $update="UPDATE departement SET name='.$this->name.', abreviation='.$this->abreviation.' WHERE id='$this->id' ";
                     mysql_query ($update);
                 }
        }			
        else {
        	if ($this->validate()) {
            mysql_query ("INSERT INTO departement VALUES ('','".$this->name."','".$this->abreviation."')");
            $this->reset();
            //return $this->getDepartement(mysql_insert_id());
          }
        }
    }

    public function loadDepartementByID($id) {
        
        $select = "SELECT * FROM departement WHERE id = '$id'";
        $resource = mysql_query($select);
        $this->setValues(mysql_fetch_array($resource));
    }

    public function getAllDepartements() {
        
        $select = "SELECT * FROM departement";
        $resource = mysql_query($select);
		$departements = array();
        while($departement = mysql_fetch_object($resource)) {
        	  $departements[] = $departement;
        } 
        return $departements; 
    }    

    private function validate() {

        if (empty($this->name)) {
             $this->addError("name","Saisissez le nom");
        }
        if (empty($this->abreviation)) {
             $this->addError("abreviation","Saisissez l'abreviation");
        }
          if(count($this->error) > 0) {
            return false;
        } else {
            return true;
        }      
    }

   private function addError($index, $error) {
        $this->error[$index] =  $error;
    }

    public function getError($index) { 
      if(!empty($this->error[$index])) {
        return '<div class="alert alert-error">'.$this->error[$index].'</div>';
      }
    }
    public function hasError() {
       return count($this->error) > 0 ? true : false;
    }

    public function getName(){
    	return $this->name;
    }
    public function getId(){
        return $this->id;
    }    
    public function getAbreviation(){
    	return $this->abreviation;
    }
}
